package com.nari.ncps.screen.service.impl.dryport;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.dryport.DryportSafetyenvSkylight;
import com.nari.ncps.screen.mapper.dryport.DryportSafetyenvSkylightMapper;
import com.nari.ncps.screen.service.dryport.DryportSafetyenvSkylightService;
import com.nari.ncps.screen.vo.dryport.SkylightVO;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 天窗检修情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class DryportSafetyenvSkylightServiceImpl extends ServiceImpl<DryportSafetyenvSkylightMapper, DryportSafetyenvSkylight> implements DryportSafetyenvSkylightService {

    @Override
    public SkylightVO getSkylightStatistics(Integer year) {
        // 设置默认年份为当前年
        if (year == null) {
            year = LocalDate.now().getYear();
        }
        
        // 使用MyBatis Plus查询dateType=0的年度数据
        QueryWrapper<DryportSafetyenvSkylight> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date_type", 0)
                    .eq("del_flag", 0)
                    .eq("year", year);
        
        List<DryportSafetyenvSkylight> entityList = this.list(queryWrapper);
        
        SkylightVO vo = new SkylightVO();
        
        // 如果数据库为空，返回空对象
        if (entityList == null || entityList.isEmpty()) {
            return vo;
        }
        
        // 对相同年份的数据进行求和
        int totalPlanned = 0;
        int totalCompleted = 0;
        int totalTempCompleted = 0;
        
        for (DryportSafetyenvSkylight entity : entityList) {
            if (entity.getSkylightPlanned() != null) {
                totalPlanned += entity.getSkylightPlanned();
            }
            if (entity.getSkylightCompleted() != null) {
                totalCompleted += entity.getSkylightCompleted();
            }
            if (entity.getTempSkylightCompleted() != null) {
                totalTempCompleted += entity.getTempSkylightCompleted();
            }
        }
        
        // 设置汇总后的值
        vo.setSkylightPlanned(totalPlanned);
        vo.setSkylightCompleted(totalCompleted);
        vo.setTempSkylightCompleted(totalTempCompleted);
        
        // 计算检修完成率 = 完成量 / 计划量 * 100
        if (totalPlanned > 0) {
            BigDecimal completionRate = new BigDecimal(totalCompleted)
                .divide(new BigDecimal(totalPlanned), 4, RoundingMode.HALF_UP)
                .multiply(new BigDecimal(100))
                .setScale(2, RoundingMode.HALF_UP);
            vo.setCompletionRate(completionRate);
        } else {
            vo.setCompletionRate(BigDecimal.ZERO);
        }
        
        return vo;
    }

}
